
import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import {getUserList, toEditUpdateInfo, toDeleteInfo, toAddUserInfo} from './service';


import {SingleUserInfoType} from './data';

export interface UserListDataType {
  userArr: SingleUserInfoType[];
  meta: {
    total: number;
    per_page: number;
    page: number;
  }
}


interface UserModelType {
  namespace: 'tablePro';
  state: UserListDataType;
  reducers: {
    updateDemoData: Reducer;
  };
  effects: {
    queryRemoteDemoUserList: Effect;
    editUpdateInfo: Effect;
    deleteUserInfo: Effect;
    addUserInfo: Effect;
  },
  subscriptions: {
    setup: Subscription,
  }
}



const UserModel: UserModelType = {

  namespace: 'tablePro',

  state: {
    userArr: [],
    meta: {
      total: 0,
      per_page: 50,
      page: 1,
    }
  },

  reducers: {
    updateDemoData(state, {type, payload}) {
      console.log('reducers更新状态', payload);
      // 为了简写, 因此payload必须要封装成对象
      return {
        ...state,
        ...payload
      };
    },

    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },

  effects: {

    *queryRemoteDemoUserList({ payload }, { call, put, select}) {

      const {page, per_page} = yield select((state: any) => state.tablePro.meta);
      const resp = yield call(getUserList, {page, per_page});
      console.log('操作了----重新刷新----调用effects返回数据', resp.data);

      if (resp){
        yield put({
          type: 'updateDemoData',
          payload: {
            userArr: resp.data,
            meta: resp.meta
          }
        })
      }
    },




    *editUpdateInfo( { payload: {id, values} }, { call, put, select }) {
      console.log('编辑更新',values, id);
      const  res = yield call(toEditUpdateInfo, {id, values});
      console.log('model层----编辑更新', res);

      yield put({
        type: 'queryRemoteDemoUserList',
      })
    },


    *deleteUserInfo({payload: {id}}, { call, put, select}) {

      const data = yield call(toDeleteInfo, {id});
      console.log('model层----删除', data);

      yield put({
        type: 'queryRemoteDemoUserList',
      })
    },


    *addUserInfo({payload: {values}}, {call, put}){
      console.log('添加传参', values);
      const data = yield call(toAddUserInfo, {values});

      yield put({
        type: 'queryRemoteDemoUserList',
      })
    }

  },

  subscriptions: {
    setup({ dispatch, history }, done: any) {
      return history.listen((location, action) => {
        if (location.pathname === '/tablePro') {

          // console.log('subscriptions');

          // 由于dispatch分发action，则action是一个对象。形如： { type: 'queryRemoteDemoUserList', payload: {} }
          // dispatch({
          //   // 异步
          //   type: 'queryRemoteDemoUserList',
          //
          //   // 同步
          //   // type: 'updateDemoData',
          // });


        }
      });
    },
  },
};

export default UserModel;
